<?php

namespace App\Http\Middleware;

use Closure;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class RefreshToken extends BaseMiddleware
{
    public function handle($request, Closure $next)
    {
        $this->checkForToken($request);

        try {
            $payload = $this->auth->parseToken()->getPayload()->toArray();
            $role = $payload['role'];
            if (auth($role)->check()) {
                $expired = $payload['exp'] - time();
                // 如果 token 过期时间小于 30 分钟，则刷新token（避免用户重新登录）
                if (30 * 60 > $expired) {
                    logs()->info('expired >> ' . $expired);
                    $token = $this->auth->refresh();
                    // 将新的 token 写入响应的 Authorization 头部
                    return $this->setAuthenticationHeader($next($request), $token);
                }
                // 继续传递请求
                return $next($request);
            }
            throw new UnauthorizedHttpException('jwt-auth', '未登录');
        } catch (JWTException $exception) {
            throw new UnauthorizedHttpException('jwt-auth', '令牌已失效，请重新登录', null, 401);
        }
    }
}
